package com.btb.adapter.service;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.btb.adapter.mapper.TaskConfigMapper;
import com.btb.adapter.model.TaskConfig;
import com.btb.adapter.model.TaskConfigExample;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class TaskConfigService {
	private LoadingCache<String,TaskConfig> taskConfigCache = CacheBuilder.newBuilder().
	        expireAfterWrite(5L, TimeUnit.MINUTES).
	        maximumSize(5000L).
	        build(new CacheLoader<String, TaskConfig>() {
	            @Override
	            public TaskConfig load(String taskName) throws Exception {
	                return findConfigByTaskName(taskName);
	            }
	        });
	@Autowired
	private TaskConfigMapper taskConfigMapper;

	public List<TaskConfig> queryAll(){
		return taskConfigMapper.selectByExample(new TaskConfigExample());
	}
	public List<TaskConfig> queryNotifyRemoteTask(String taskName) {
		TaskConfigExample example = new TaskConfigExample();
		example.createCriteria().andTaskNameEqualTo(taskName);
		return taskConfigMapper.selectByExample(example);
	}
	public TaskConfig findConfigByTaskNameCache(String taskName) {
		try {
			TaskConfig taskConfig = taskConfigCache.get(taskName);
			if(Objects.nonNull(taskConfig)){
				return taskConfig;
			}
		} catch (ExecutionException e) {
			log.error("findConfigByTaskName err {}", e.getMessage(), e);
		}
		TaskConfig taskConfigQuery = findConfigByTaskName(taskName);
		taskConfigCache.put(taskName, taskConfigQuery);
		return taskConfigQuery;
	}
	public TaskConfig findConfigByTaskName(String taskName) {
		TaskConfigExample example = new TaskConfigExample();
		example.createCriteria().andTaskNameEqualTo(taskName);
		TaskConfig taskConfigQuery = taskConfigMapper.selectByExample(example).stream().findAny().orElse(null);
		return taskConfigQuery;
	}

	public int updateStartBlockNumber(Integer id, Long startBlockNumber) {
		TaskConfig config = TaskConfig.builder().id(id).startBlockNumber(startBlockNumber).build();
		return taskConfigMapper.updateByPrimaryKeySelective(config);
	}
}
